package com.lpf.www.common.utils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * @Author lpf
 * @Date 2021/12/31 下午7:12
 * @ProjectName live-streaming-os
 * @Version 1.0
 * @Description:
 */
public class CookieTools {
    public void save(String name, String value, int time) {
        try {
            value = URLEncoder.encode(value, "utf-8");
            Cookie cookie = new Cookie(name, value);
            cookie.setMaxAge(time);
            RequestResponseBox.getResponse().addCookie(cookie);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    public String getCookie(String name) {
        String value = "";
        HttpServletRequest request = RequestResponseBox.getRequest();
        Cookie[] cookies = request.getCookies();
        if (cookies != null){
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(name)){
                    try {
                        value = cookie.getValue();
                        value = URLDecoder.decode(value, "utf-8");
                        break;
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return value;
    }

    public void deleteCookie(String name){
        this.save(name, "", 0);
    }
}
